package com.special.ResideMenuDemo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.os.Bundle;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

import weather.GpsSearch;
import weather.QueryWeather;
import weather.Weather;
import weather.WeatherTask;

/**
 * User: sirius
 * Date: 17-3-13
 * Time: 下午1:33
 * Mail: sirius_swu@163.com
 */
public class HomeFragment extends Fragment {
    // 声明JSON对象
    private JSONObject jsonObject;
    // 初始化UI组件
    private View parentView;
    private ImageView ivDeleteText;
    private EditText etSearch;
    private ImageView imageView;
    private TextView location;
    private TextView weather;
    private TextView tem;
    private TextView level;
    private Button btnSearch;
    private ImageView discover;
    private ImageView variable;
    private ImageView robot;
    private ImageView fit;
    private ImageView controll;
    private ImageView video;
    private ImageView forum;
    private ImageView message;
    private ImageView pot;
    // 声明控制变量
    private String picVar;
    private String locationVar;
    private String weatherVar;
    private String temVar;
    private String levelVar;
    private String city;
    WeatherTask weatherTask;
    // 加载网络图片
    private byte[] picByte;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 启动子线程
//        new Thread(networkTask).start();

        // UI控件关联
        parentView = inflater.inflate(R.layout.home, container, false);
        ivDeleteText = (ImageView) parentView.findViewById(R.id.ivDeleteText);
        etSearch = (EditText) parentView.findViewById(R.id.etSearch);
        imageView = (ImageView) parentView.findViewById(R.id.imageView);
        location = (TextView) parentView.findViewById(R.id.location);
        weather = (TextView) parentView.findViewById(R.id.weather);
        tem = (TextView) parentView.findViewById(R.id.tem);
        level = (TextView) parentView.findViewById(R.id.level);
        btnSearch = (Button) parentView.findViewById(R.id.btnSearch);
        discover = (ImageView) parentView.findViewById(R.id.discover);
        variable = (ImageView) parentView.findViewById(R.id.variable);
        robot = (ImageView) parentView.findViewById(R.id.robot);
        fit = (ImageView) parentView.findViewById(R.id.fit);
        controll = (ImageView) parentView.findViewById(R.id.controll);
        video = (ImageView) parentView.findViewById(R.id.video);
        forum = (ImageView) parentView.findViewById(R.id.forum);
        message = (ImageView) parentView.findViewById(R.id.message);
        pot = (ImageView) parentView.findViewById(R.id.pot);

        // 搜索框叉号的显示和隐藏及清除效果
        ivDeleteText.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                etSearch.setText("");
            }
        });

        etSearch.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub

            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    ivDeleteText.setVisibility(View.GONE);
                } else {
                    ivDeleteText.setVisibility(View.VISIBLE);
                }
            }
        });

        // 搜索城市
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                city = etSearch.getText().toString();
                etSearch.setText("");
                new Thread(networkTask).start();
            }
        });

        // 机器人
        robot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Toast.makeText(getActivity(), "Robort", Toast.LENGTH_SHORT).show();
                Intent intent1 = new Intent();
                intent1.setClass(getActivity(), RobotActivity.class);
                startActivity(intent1);
            }
        });

        // 发现
        discover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent2 = new Intent();
                intent2.setClass(getActivity(), DiscoverActivity.class);
                startActivity(intent2);
            }
        });

        // 盆友圈
        pot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent3 = new Intent();
                intent3.setClass(getActivity(), PotActivity.class);
                startActivity(intent3);
            }
        });

        // 消息
        message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent4 = new Intent();
                intent4.setClass(getActivity(), MessageActivity.class);
                startActivity(intent4);
            }
        });

        forum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent5 = new Intent();
                intent5.setClass(getActivity(), ForumActivity.class);
                startActivity(intent5);
            }
        });
        return parentView;
    }

    /*
    * 消息传递机制Handler，将子线程数据传输给主线程
    * */
    private android.os.Handler mHandler = new android.os.Handler() {
        public void handleMessage (Message msg) {//此方法在ui线程运行
            switch (msg.what) {
                case 0:
                    location.setText((CharSequence) msg.obj);
                    weather.setText(weatherVar);
                    tem.setText(temVar);
                    level.setText(levelVar);
                    break;
                case 1:
                    if (msg.what == 1) {
                        if (picByte != null) {
                            Bitmap bitmap = BitmapFactory.decodeByteArray(picByte, 0, picByte.length);
                            imageView.setImageBitmap(bitmap);
                        }
                    }
                    break;
            }

        }
    };

    /**
     * 网络操作相关的子线程
     */
    Runnable networkTask = new Runnable() {
        @Override
        public void run() {
            // TODO
            // 在这里进行 http request.网络请求相关操作
            if (city != null) {
                QueryWeather weather = new QueryWeather(city);
                jsonObject = weather.retJson();
            } else {
                GpsSearch gpsSearch = new GpsSearch(getActivity());
                jsonObject = gpsSearch.retJson();
            }
            JSONObject locResult = jsonObject.getJSONObject("showapi_res_body").getJSONObject("cityInfo");
            locationVar = locResult.getString("c7")+"省"+locResult.getString("c3")+"市";
            JSONObject weather_tem = jsonObject.getJSONObject("showapi_res_body").getJSONObject("now");
            weatherVar = weather_tem.getString("weather");
            temVar = weather_tem.getString("temperature")+"\u2103";
            picVar = weather_tem.getString("weather_pic");
            System.out.println("URL"+picVar);
            JSONObject levResult = jsonObject.getJSONObject("showapi_res_body").getJSONObject("f1");
            levelVar = levResult.getString("jiangshui");
            Message msg = new Message();
            msg.what = 0;
            msg.obj = locationVar;
            mHandler.sendMessage(msg);

            try {
                URL url = new URL(picVar);
                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                conn.setRequestMethod("GET");
                conn.setReadTimeout(10000);

                if (conn.getResponseCode() == 200) {
                    InputStream fis =  conn.getInputStream();
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte[] bytes = new byte[1024];
                    int length = -1;
                    while ((length = fis.read(bytes)) != -1) {
                        bos.write(bytes, 0, length);
                    }
                    picByte = bos.toByteArray();
                    bos.close();
                    fis.close();

                    Message message = new Message();
                    message.what = 1;
                    mHandler.sendMessage(message);
                }


            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * 解析
     *
     * @throws JSONException
     */
    private String returnValue() {
        /******************* 解析 ***********************/
        JSONObject location = jsonObject.getJSONObject("showapi_res_body").getJSONObject("cityInfo");

        // 初始化list数组对象
//        String list = new String();
        // 初始化map数组对象
//        map.put("imageView", jsonObject.getJSONObject("showapi_res_body").getJSONObject("f6").getString("day_weather_pic"));
//        locationVar = location.getString("c7")+"省"+location.getString("c3")+"市";
//        map.put("weather", jsonObject.getJSONObject("showapi_res_body").getString("day_weather"));
//        map.put("level", jsonObject.getJSONObject("showapi_res_body").getString("title"));
        locationVar = "广东省珠海市";
        return "广东省珠海市";
    }

    /**
     * readParse（String）从服务器端获取数据
     * Analysis（String）解析json数据
     */
//    private void resultJson() {
//        try {
//            allData = Analysis();
//            Iterator<HashMap<String, Object>> it = allData.iterator();
//            while (it.hasNext()) {
//                Map<String, Object> ma = it.next();
////                String imageViewVar = (String) ma.get("imageView");
//                locationVar = (String) ma.get("province")+"省"+ma.get("city")+"市";
////                String weatherVar = (String) ma.get("weather");
////                String levelVar = (String) ma.get("level");
//            }
//        } catch (JSONException e) {
//            e.printStackTrace();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 获取网落图片资源
     * @param url
     * @return
     */
    public static Bitmap getHttpBitmap(String url){
        URL myFileURL;
        Bitmap bitmap=null;
        try{
            myFileURL = new URL(url);
            //获得连接
            HttpURLConnection conn=(HttpURLConnection)myFileURL.openConnection();
            //设置超时时间为6000毫秒，conn.setConnectionTiem(0);表示没有时间限制
            conn.setConnectTimeout(6000);
            //连接设置获得数据流
            conn.setDoInput(true);
            //不使用缓存
            conn.setUseCaches(false);
            //这句可有可无，没有影响
            //conn.connect();
            //得到数据流
            InputStream is = conn.getInputStream();
            //解析得到图片
            bitmap = BitmapFactory.decodeStream(is);
            //关闭数据流
            is.close();
        }catch(Exception e){
            e.printStackTrace();
        }

        return bitmap;

    }
}
